package utils

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"strings"
)
//把请求体中的参数解析成map结构，方便操作
func Params2Map(c *gin.Context) (map[string]interface{}, error) {
	params_m := make(map[string]interface{})
	method := strings.ToLower(c.Request.Method)
	if method == "get" {
		rowParams := c.Request.URL.RawQuery
		params := strings.Split(rowParams, "&")
		for _, p := range params {
			k_v := strings.Split(p, "=")
			if len(k_v) == 2 {
				params_m[k_v[0]] = k_v[1]
			}
		}
		return params_m, nil
	} else if method == "post" {
		params_b, _ := ioutil.ReadAll(c.Request.Body)
		params := string(params_b)

		ct := c.Request.Header.Get("Content-Type")
		if ct == "application/x-www-form-urlencoded" {
			for _, v := range strings.Split(params, "&") {
				kv := strings.Split(v,"=")
				params_m[kv[0]] = kv[1]
			}
			return params_m,nil
		} else if ct =="application/json" {
			err := json.Unmarshal(params_b, &params_m)
			if err != nil {
				fmt.Println("JsonToMap error: ", err)
			}
			return params_m,nil
		} else {
			fmt.Println("content-type not supported")
			return nil,fmt.Errorf("content-type not supported")
		}
	}
	return nil, fmt.Errorf("method not supported")
}


